package com.junyu.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junyu.common.ResultCodeEnum;
import com.junyu.exception.LoginException;
import com.junyu.interceptor.ThreadLocalUtil;
import com.junyu.mapper.LoginMapper;
import com.junyu.pojo.dto.ChangeEm;
import com.junyu.pojo.dto.ChangePw;
import com.junyu.pojo.dto.FindPw;
import com.junyu.pojo.entity.LoginLog;
import com.junyu.pojo.entity.User;
import com.junyu.pojo.dto.LoginParam;
import com.junyu.pojo.vo.LoginLogVo;
import com.junyu.service.LogService;
import com.junyu.service.LoginService;
import com.junyu.util.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 *登录接口实现类
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, User> implements LoginService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private HttpServletResponse httpServletResponse;

    @Autowired
    private LogService logService;


    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 登录功能实现
     * @param loginParam 登录参数对象
     * @return LoginLogVo 登录日志vo对象
     */
    @Override
    public LoginLogVo login(LoginParam loginParam) {
        //校验登录参数是否为空
        if (loginParam == null) {
            throw new LoginException(ResultCodeEnum.LOGIN_PARAM_ERROR);
        }
        User dbUser = new User();
        //用户名和密码登录
        if (!loginParam.getUsernameOrEmail().contains("@")) {
            //校验用户名和密码
            if (StringUtils.isEmpty(loginParam.getUsernameOrEmail()) || StringUtils.isEmpty(loginParam.getPassword())) {
                throw new LoginException(ResultCodeEnum.LOGIN_PARAM_ERROR);
            }
            //根据用户名查询数据库
            dbUser = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, loginParam.getUsernameOrEmail()));
        }

        //否则邮箱和密码登录
        else {
            //校验邮箱和密码
            if (StringUtils.isEmpty(loginParam.getUsernameOrEmail()) || StringUtils.isEmpty(loginParam.getPassword())) {
                throw new LoginException(ResultCodeEnum.LOGIN_PARAM_ERROR);
            }
            //根据邮箱查询数据库
            dbUser = this.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, loginParam.getUsernameOrEmail()));
        }
        //用户不存在
        if (dbUser == null) {
            throw new LoginException(ResultCodeEnum.USER_NOT_EXIST);
        }
        //用户存在
        //密码不正确
        if (!dbUser.getPassword().equals(DigestUtils.md5DigestAsHex(loginParam.getPassword().getBytes()))) {
            throw new LoginException(ResultCodeEnum.PASSWORD_ERROR);
        }
        //密码正确
        //根据用户id查询是否存在登录状态
        String oldToken = this.redisTemplate.opsForValue().get("user:login:" + dbUser.getId());
        if (StringUtils.isNotEmpty(oldToken)) {
            //删除redis中的token
            redisTemplate.delete("user:login:" + oldToken);
        }
        //生成并保存token
        String token = IdUtil.createSnowflake(1, 1).nextIdStr();
        dbUser.setPassword("");
        //以token为键，用户信息为value
        redisTemplate.opsForValue().set("user:login:" + token, JSONObject.toJSONString(dbUser), 60, TimeUnit.MINUTES);
        //以用户id为
        redisTemplate.opsForValue().set("user:login:" + dbUser.getId(), token, 60, TimeUnit.MINUTES);
        //记录登录ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ipAddress = IpUtil.getIpAddress(request);


        //登录成功返回上一次登录时间和ip
        LoginLog loginLog = logService.findLogByUserName(dbUser.getUserName());
        LoginLogVo loginLogVo = new LoginLogVo();
        if (loginLog != null) {
            loginLogVo.setLastLoginIp(loginLog.getIpAddress());
            loginLogVo.setLastLoginDate(loginLog.getCreateTime());
            loginLogVo.setUsername(dbUser.getUserName());
        }
        loginLogVo.setToken(token);
        //保存登录日志
        LoginLog loginLogs = new LoginLog();
        loginLogs.setUserId(dbUser.getId());
        loginLogs.setIpAddress(ipAddress);
        loginLogs.setOperator(dbUser.getUserName());
        this.logService.saveLog(loginLogs);
        return loginLogVo;
    }

    /**
     * 修改密码功能实现
     * @param changePw 修改密码参数
     */
    @Override
    public void changePassword(ChangePw changePw) {
        if (changePw.getNewPassword() == null || !changePw.getNewPassword().matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$")) {
            throw new LoginException(ResultCodeEnum.PASSWORD_FORMAT_ERROR);
        }
        //查询用户是否存在
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, changePw.getEmail()));
        if (user == null) {
            throw new LoginException(ResultCodeEnum.USER_NOT_EXIST);
        }
        if (changePw.getOldPassword() != null && !user.getPassword().equals(DigestUtils.md5DigestAsHex(changePw.getOldPassword().getBytes()))) {
            throw new LoginException(ResultCodeEnum.USER_OLD_PASSWORD_ERROR);
        }
        user.setPassword(DigestUtils.md5DigestAsHex(changePw.getNewPassword().getBytes()));
        // 修改密码
        this.updateById(user);
    }


    /**
     * 修改邮箱功能实现
     * @param changeEm 修改邮箱参数
     */
    @Override
    public void changeEmail(ChangeEm changeEm) {
        //校验邮箱格式
        if (!changeEm.getNewEmail().matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
            throw new LoginException(ResultCodeEnum.EMAIL_FORMAT_ERROR);
        }
        //查询用户是否存在
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, changeEm.getUserName()));
        if (user == null) {
            throw new LoginException(ResultCodeEnum.USER_NOT_EXIST);
        }
        user.setEmail(changeEm.getNewEmail());
        // 修改邮箱
        this.updateById(user);
    }


    /**
     * 生成验证码功能实现
     * @param userName 用户名
     * @param email 邮箱
     */
    @Override
    public void getCode(String userName, String email) {
        // 查询响应用户信息
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, userName).eq(User::getEmail, email));
        // 判断用户是否存在
        if (user == null) {
            throw new LoginException(ResultCodeEnum.USER_NOT_EXIST);
        }
        // 生成随机6位数的验证码
        String code = RandomUtil.randomNumbers(6);
        //发送验证码
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(email);
            message.setTo(email);
            message.setSubject("找回密码验证码");
            message.setText("验证码是" + code);
            //发送验证码
            javaMailSender.send(message);

            // 存redis（5min）
            redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);

        } catch (Exception e) {
            throw new LoginException(ResultCodeEnum.EMAIL_SEND_ERROR);
        }
    }

    /**
     * 找回密码功能实现
     * @param findPw 找回密码参数
     */
    @Override
    public void findPassword(FindPw findPw) {
        //校验验证码
        String redisCode = this.redisTemplate.opsForValue().get(findPw.getEmail());
        if (StringUtils.isEmpty(redisCode)) {
            throw new LoginException(ResultCodeEnum.USER_NOT_EXIST);
        }
        if (redisCode.equals(findPw.getCode())) {
            //修改密码
            User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, findPw.getEmail()));
            user.setPassword(DigestUtils.md5DigestAsHex(findPw.getNewPassword().getBytes()));
            this.updateById(user);
            //删除验证码
            redisTemplate.delete(findPw.getEmail());
        }
    }

    /**
     * 退出功能实现
     */
    @Override
    public void logout() {
        User user = ThreadLocalUtil.get();
        //根据用户id查询是否存在登录状态
        String oldToken = this.redisTemplate.opsForValue().get("user:login:" + user.getId());
        if (StringUtils.isNotEmpty(oldToken)) {
            //删除redis中的token
            redisTemplate.delete("user:login:" + oldToken);
        }
    }

    /**
     * 记住密码功能实现
     * @param password 密码
     * @param userName 邮箱
     */
    @Override
    public void rememberPassword(String password, String userName) {
//        //校验密码和邮箱
//        if (password == null || !password.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$")) {
//            throw new LoginException(ResultCodeEnum.PASSWORD_FORMAT_ERROR);
//        }
//        if (userName == null || !userName.matches("^[a-zA-Z][a-zA-Z0-9_-]{5,}$")) {
//            throw new LoginException(ResultCodeEnum.USER_NAME_FORMAT_ERROR);
//        }
//
//        //将密码存储到redis 并设置过期时间为五分钟
//        redisTemplate.opsForValue().set(userName, password, 5, TimeUnit.MINUTES);
        Cookie cookieName = new Cookie("userName",userName);
        Cookie cookiePw = new Cookie("password",password);
        cookieName.setMaxAge(300);
        cookiePw.setMaxAge(300);
        httpServletResponse.addCookie(cookiePw);
        httpServletResponse.addCookie(cookieName);
    }
}

